const BASE_URL='http://172.16.10.10:8099';

function  formatobj(params) {
    let str="";
    for(let key in params){
        str+=key+"="+params[key]+"&";
    }
    str=str.substring(0,str.length-1);
    return str;
}

const http={
    get:function(url,data,callback){
        let xhr=new XMLHttpRequest();
        xhr.open('get',BASE_URL+url+"?"+formatobj(data));
        xhr.send();
        xhr.onreadystatechange=function() {
            if(xhr.readyState==4 && xhr.status==200){
                callback(JSON.parse(xhr.responseText));
            }
        }
    },

    post:function(url,data,callback) {
        let xhr=new XMLHttpRequest();
        xhr.open('post',BASE_URL+url);
        // 模仿form表单
        // xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
        // xhr.send(formatobj(data));
        // json方式 
        xhr.setRequestHeader('Content-type','application/json');
        xhr.send(JSON.stringify(data));
        xhr.onreadystatechange=function(){
            if(xhr.readyState==4 && xhr.status==200){
                callback(JSON.parse(xhr.responseText));
            }
        }
    },

    ajax:function(obj){
        if(obj.type=="get"){
            this.get(obj.url,obj.data,obj.sucess);
        }
        else if(obj.type=="post"){
            this.post(obj.url,obj.data,obj.sucess);
        }
    },

    //请求参数文件
    uploadFile: function (url, fdKey, fdValue, success) {
        const xhr = new XMLHttpRequest();
        //创建form表单
        const fd = new FormData();
        // 给form 表单 添加 input 框 同时写入了数据
        fd.append(fdKey, fdValue);
        xhr.open('POST', BASE_URL+url);
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && xhr.status === 200) {
                const resData = JSON.parse(xhr.responseText)
                success(resData)
            }
        }
        xhr.send(fd);
    } 
}
window.http=http;